<template>
    <Frame
        title="签署《入驻承诺书》"
        :steps="steps"
        :current-index="step"
        :err-msg="errMsg"
    >
        <FrameContent
            v-if="step === 0"
            img-full
            btn-text="签署"
            :pdfUrl="PDFUrl"
            :loading="sendCAPTCHALoading"
            @on-confirm="SMSVerification"
        />
        <FrameContent
            v-if="step === 1"
            img-full
            btn-text="完成"
            :pdfUrl="successPDFUrl"
            @on-confirm="handleSuccess"
        />
        <SMSPopup
            ref="SMSPopup"
            v-model="SMSPopupVisible"
            :loading="checkLoading"
            :countdown="countdown"
            @on-re-accept="SMSVerification"
            @on-submit="handleSubmitMsgCode"
        />
    </Frame>
</template>

<script>
import HeadStep from '@/components/HeadStep';
import countdown from '@/mixins/countdown.js';
import {
    restful_api,
    verifyCode_api,
    sendVerificationCode_api,
    checkCorp_api,
    checkScene_api,
    signContract_api,
    authorize_api,
} from '@/api';
export default {
    name: 'SignForDeploy',
    components: { HeadStep },
    mixins: [countdown],
    props: {
        userType: Number,
        default() {
            return 3;
        },
    },
    data() {
        return {
            // 错误消息
            errMsg: '',

            // 用户信息
            token: '',
            srcOrderNo: '', // 流水号
            user: {}, // 用户信息

            steps: ['签署协议', '完成签署'],
            step: 0,

            sendCAPTCHALoading: false, // 调用发送验证码接口 loading

            // 短信弹窗
            SMSPopupVisible: false,
            checkLoading: false,

            PDFUrl: '',
            successPDFUrl: '',
            projectCode: '', // 项目代码
        };
    },
    async mounted() {
        this.getUserData();
    },
    methods: {
        handleSuccess() {
            try {
                app.back();
            } catch (e) {
                window.close();
            }
        },

        /**
         * 标记协议已签署
         */
        async completeSign() {
            let params = {
                srcOrderNo: this.srcOrderNo,
                token: this.token,
            };
            await restful_api({ methodId: 'TP350008', params });
        },

        /**
         * 协议签署
         */
        async handleSignContract() {
            try {
                let data = {
                    srcOrderNo: this.srcOrderNo,
                    createContractVO: {
                        templateId: 'QT_11942',
                        signInfos: [
                            {
                                userId: this.user.userId,
                                authorizationTime: this.$utils.formatDateTime(
                                    new Date(),
                                    'yyyyMMddhhmmss'
                                ),
                                location: window.location.origin,
                                signLocation: 'Signature1',
                                projectCode: this.projectCode,
                                isProxySign: 1,
                            },
                        ],
                        textValueInfo: {
                            IDCard: this.mztUser.cardNum,
                            user: this.mztUser.name,
                        },
                    },
                };
                signContract_api(data, {
                    accessToken: this.accessToken,
                    userType: this.userType,
                }).then((res) => {
                    if (res) {
                        const { fileBase64 } = res;
                        this.checkLoading = false;
                        this.SMSPopupVisible = false;
                        this.step++;
                        this.successPDFUrl = fileBase64;
                        this.completeSign();
                    }
                });
            } catch (e) {
                this.checkLoading = false;
                this.SMSPopupVisible = false;
                this.$toast(e);
            }
        },

        /**
         * 提交短信验证码
         */
        async handleSubmitMsgCode(code) {
            try {
                this.checkLoading = true;
                let data = {
                    userId: this.user.userId,
                    projectCode: this.projectCode,
                    checkCode: code,
                };
                await verifyCode_api(data);
                // 签署
                this.handleSignContract();
            } catch (e) {
                this.checkLoading = false;
                this.$refs.SMSPopup.reset();
                this.$toast(e);
            }
        },

        /**
         * 发送验证码
         */
        async SMSVerification() {
            try {
                this.sendCAPTCHALoading = true;
                let data = {
                    userId: this.user.userId,
                    projectCode: this.srcOrderNo,
                };
                let { projectCode } = await sendVerificationCode_api(data);

                this.projectCode = projectCode;
                this.sendCAPTCHALoading = false;
                // 倒计时
                this.handleCountdown();
                // 弹窗
                this.SMSPopupVisible = true;
            } catch (e) {
                this.sendCAPTCHALoading = false;
                this.$toast(e);
            }
        },

        /**
         * 获取空协议
         */
        async handleAuthorization() {
            let params = {
                token: this.token,
                srcOrderNo: this.srcOrderNo,
                userType: this.userType,
            };
            try {
                let res = await restful_api({ methodId: 'TP350008', params });
                this.PDFUrl = res.fileStream;
            } catch (e) {
                console.log('handleAuthorization err:', e);
            }
        },

        /**
         * 获取用户信息
         */
        async getUserByAccessToken(accessToken) {
            try {
                this.accessToken = accessToken;
                this.user = await authorize_api(
                    {
                        authenticationMode: '公安部',
                    },
                    { accessToken, userType: this.userType }
                );
                this.handleAuthorization();
            } catch (e) {
                this.$toast(e);
            }
        },

        /**
         * 检查信息
         */
        async checkRole() {
            let data = {
                certCode: this.mztUser.cardNum,
                certName: this.mztUser.name,
                phone: this.mztUser.mobile,
                srcOrderNo: this.srcOrderNo,
                token: this.token,
            };
            let interfaceDict = { 3: checkCorp_api, 4: checkScene_api };
            let interfaceType = interfaceDict[this.userType];
            try {
                // 角色权限校验
                let { resultCode } = await interfaceType(data);

                if (resultCode === '0') {
                    // 获取用户信息
                    return this.getUserByAccessToken(this.token);
                }
                let msgDict = [
                    '',
                    '法人代表匹配不一致',
                    '法人代表名下企业与申报企业信息不一致',
                ];
                this.errMsg = msgDict[resultCode];
            } catch (e) {
                console.log('2222e', e);

                this.errMsg = e;
            }
        },

        /**
         * 从 URL 获取用户信息(token, srcOrderNo)
         */
        getUserData() {
            this.token = this.$route.query.token || 'Ie0J7M34A4qog0lS';
            this.srcOrderNo =
                this.$route.query.srcOrderNo || '202212061441507571123222568';
            this.checkRole();
        },
    },
};
</script>
<style scoped></style>
